package adc.app.ui.wicket.table;

import org.apache.wicket.AttributeModifier;
import org.apache.wicket.Component;
import org.apache.wicket.MarkupContainer;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.navigation.paging.AjaxPagingNavigator;
import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractToolbar;
import org.apache.wicket.extensions.markup.html.repeater.data.table.NavigatorLabel;
import org.apache.wicket.markup.html.WebComponent;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.navigation.paging.IPageable;
import org.apache.wicket.markup.repeater.RepeatingView;
import org.apache.wicket.model.Model;

public class NavigationToolbar extends AbstractToolbar {

	private static final long serialVersionUID = 1L;
	private static final String ID_TABLE_CELL = "tableCell";
	private static final String ID_NAVIGATOR = "navigator";
	private static final String ID_NAVIGATOR_LABEL = "navigatorLabel";
	private static final String ID_LINK_REPEAT = "linkRepeat";
	private static final String ID_LINK = "link";
	private static final String ID_LINK_LABEL = "caption";
	
	private RepeatingView linkRepeat = new RepeatingView(ID_LINK_REPEAT);
	
	public NavigationToolbar(DataTable<?> table) {
		super(table);
		WebMarkupContainer span = new WebMarkupContainer(ID_TABLE_CELL);
		add(span);
		span.add(new AttributeModifier("colspan", true, new Model<String>(
				String.valueOf(table.getColumns().size()))));

		span.add(new InvPagingNavigator(ID_NAVIGATOR, table));
		span.add(new NavigatorLabel(ID_NAVIGATOR_LABEL, table));
		span.add(linkRepeat);
	}

	public String getLinkId() {
		return ID_LINK;
	}
	
	public String getLinkLabelId() {
		return ID_LINK_LABEL;
	}
	
	public void addLink(MarkupContainer link) {
		Component linkLabel = link.get(this.getLinkLabelId());
		if (linkLabel == null) {
			link.add(new WebComponent(this.getLinkLabelId()).setVisible(false));
		}
		MarkupContainer mc = new WebMarkupContainer(linkRepeat.newChildId());
		linkRepeat.add(mc.add(link).setRenderBodyOnly(true));
	}
	
	private static final class InvPagingNavigator extends AjaxPagingNavigator {

		private static final long serialVersionUID = 1L;

		public InvPagingNavigator(String id, IPageable pageable) {
			super(id, pageable);
		}

		@Override
		protected void onAjaxEvent(AjaxRequestTarget target) {
			target.add((Component) this.getPageable());
		}
		
	}
	
}
